import { photoGroupList, photoGroupCreate, photoGroupUpdate, photoGroupDelete } from '@/api/photoGroup'

const getDefaultState = () => {
  return {
    photoGroups: [],
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_LIST: (state, list) => {
    state.photoGroups = list
  },
  SET_PUSH: (state, info) => {
    state.photoGroups.push(info)
  },
  SET_UPDATE: (state, info) => {
    const index = state.photoGroups.findIndex(v => v.id == info.id)
    if (index !== -1) {
      state.photoGroups[index].name = info.name
    }
  }
}

const actions = {
  getPhotoGroups({ commit }) {
    return new Promise((resolve, reject) => {
      photoGroupList().then(response => {
        const { data } = response
        data.unshift({ id: null, name: '全部分类' })
        commit('SET_LIST', data)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  createPhotoGroup({ commit }, data) {
    return new Promise((resolve, reject) => {
      photoGroupCreate(data).then(response => {
        const { info } = response
        commit('SET_PUSH', info)
        resolve(info)
      }).catch(error => {
        reject(error)
      })
    })
  },

  updatePhotoGroup({ commit }, data) {
    return new Promise((resolve, reject) => {
      photoGroupUpdate(data).then(() => {
        commit('SET_UPDATE', data)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

